import { ref, computed, watch, type Ref } from 'vue'

export interface SortConfig {
  key: string | null
  direction: 'asc' | 'desc'
}

export interface UseTableDataOptions<T> {
  data: Ref<T[]>
  filters?: Ref<Record<string, any>>
  defaultSort?: SortConfig
  pageSize?: number
  filterFn?: (item: T, filters: Record<string, any>) => boolean
  sortFn?: (a: T, b: T, config: SortConfig) => number
}

/**
 * 通用表格数据处理 Composable
 * 处理排序、筛选、分页等常见表格操作
 */
export function useTableData<T extends Record<string, any>>(options: UseTableDataOptions<T>) {
  const {
    data,
    filters,
    defaultSort = { key: null, direction: 'asc' },
    pageSize: initialPageSize = 10,
    filterFn,
    sortFn
  } = options

  const sortConfig = ref<SortConfig>(defaultSort)
  const currentPage = ref(1)
  const pageSize = ref(initialPageSize)

  // 排序处理
  const handleSort = (key: string) => {
    let direction: 'asc' | 'desc' = 'asc'
    if (sortConfig.value.key === key && sortConfig.value.direction === 'asc') {
      direction = 'desc'
    }
    sortConfig.value = { key, direction }
  }

  // 默认筛选逻辑
  const defaultFilterFn = (item: T, filterValues: Record<string, any>): boolean => {
    for (const [key, value] of Object.entries(filterValues)) {
      if (!value || value === 'all') continue
      
      if (key === 'search') {
        const searchLower = String(value).toLowerCase()
        const matchFound = Object.values(item).some(v => 
          String(v).toLowerCase().includes(searchLower)
        )
        if (!matchFound) return false
      } else if (item[key] !== value) {
        return false
      }
    }
    return true
  }

  // 默认排序逻辑
  const defaultSortFn = (a: T, b: T, config: SortConfig): number => {
    if (!config.key) return 0
    
    const aVal = a[config.key]
    const bVal = b[config.key]
    
    if (aVal < bVal) return config.direction === 'asc' ? -1 : 1
    if (aVal > bVal) return config.direction === 'asc' ? 1 : -1
    return 0
  }

  // 筛选和排序后的数据
  const filteredData = computed(() => {
    let filtered = [...data.value]

    // 应用筛选
    if (filters?.value) {
      const appliedFilterFn = filterFn || defaultFilterFn
      filtered = filtered.filter(item => appliedFilterFn(item, filters.value))
    }

    // 应用排序
    if (sortConfig.value.key) {
      const appliedSortFn = sortFn || defaultSortFn
      filtered.sort((a, b) => appliedSortFn(a, b, sortConfig.value))
    }

    return filtered
  })

  // 分页数据
  const totalPages = computed(() => 
    Math.ceil(filteredData.value.length / pageSize.value)
  )

  const paginatedData = computed(() => {
    const startIndex = (currentPage.value - 1) * pageSize.value
    return filteredData.value.slice(startIndex, startIndex + pageSize.value)
  })

  // 分页处理
  const handlePageChange = (page: number) => {
    currentPage.value = page
  }

  const handlePageSizeChange = (size: number) => {
    pageSize.value = size
    currentPage.value = 1
  }

  // 获取排序样式类
  const getSortClass = (key: string) => {
    if (sortConfig.value.key !== key) return 'sortable'
    return `sortable ${sortConfig.value.direction}`
  }

  // 重置筛选和排序
  const resetFilters = () => {
    if (filters) {
      Object.keys(filters.value).forEach(key => {
        filters.value[key] = key === 'search' ? '' : 'all'
      })
    }
    sortConfig.value = { ...defaultSort }
    currentPage.value = 1
  }

  // 当筛选条件改变时，重置到第一页
  if (filters) {
    watch([filters, sortConfig], () => {
      currentPage.value = 1
    }, { deep: true })
  }

  return {
    // State
    sortConfig,
    currentPage,
    pageSize,
    
    // Computed
    filteredData,
    paginatedData,
    totalPages,
    
    // Methods
    handleSort,
    handlePageChange,
    handlePageSizeChange,
    getSortClass,
    resetFilters
  }
}
